package com.ocp.macro.config;


import com.ocp.macro.filter.JwtLoginFilter;
import com.ocp.macro.filter.JwtVerifyFilter;
import com.ocp.macro.handler.LoginFailedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private LoginFailedHandler loginFailedHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();// 加密规则
    }

    // WebSecurity构建目标是整个Spring Security安全过滤器FilterChainProxy
    @Override
    public void configure(WebSecurity web) {
        // 忽略 /macro/comm/** 请求头开始的
        web.ignoring().mvcMatchers("/macro/comm/**");
    }

    // 过滤链设置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors()
                .and()
                .addFilter(getJwtLoginFilter())// 登录过滤器
                .authorizeRequests()
                .antMatchers("/macro/**").authenticated()
                .and()
                .addFilter(new JwtVerifyFilter(super.authenticationManager(), redisTemplate)) //认证路径访问前进行身份认证
                .sessionManagement() // session管理
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 不创建session;
    }

    /**
     * 登录过滤器类
     * @return 登录过滤器类实例
     */
    public JwtLoginFilter getJwtLoginFilter() throws Exception {
        JwtLoginFilter jwtLoginFilter = new JwtLoginFilter(super.authenticationManager(), redisTemplate);
        jwtLoginFilter.setAuthenticationFailureHandler(loginFailedHandler);
        return jwtLoginFilter;
    }

}
